package com.module.product.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import base.util.StringUtil;

import com.module.product.ProductService;
import com.module.product.vo.EntProduct;

public class ProductImportServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private final int maxPostSize = 1000 * 1024 * 1024;

	private final static String OPT_ERRORMSG = "1;导入失败！";

	private final static String OPT_OKMSG = "2;导入成功！";

	private final static String FORMAR_ERROR = "1;文件格式不正确！";

	SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmm");
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public void init(ServletConfig config) throws ServletException {
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			request.setCharacterEncoding("UTF-8");// 设置request字符编码
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		response.setContentType("text/html;charset=UTF-8");
		String id = request.getParameter("id");
		if (id != null && id.equals("model")) {
			this.exportModel(request, response);
		} else {
			this.productImport(request, response);
		}

	}

	@SuppressWarnings("rawtypes")
	private void productImport(HttpServletRequest request,
			HttpServletResponse response) {
		String msg = null;
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload fileUp = new ServletFileUpload(factory);
			fileUp.setSizeMax(maxPostSize);
			List items = fileUp.parseRequest(request);
			Iterator iter = items.iterator();
			InputStream stream = null;
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					stream = item.getInputStream();
					msg = this.importProduct(stream, request);// 产品导入
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = OPT_ERRORMSG;
		} finally {
			this.returnMsg(response, msg);
		}
	}

	private void returnMsg(HttpServletResponse response, String msg) {
		PrintWriter pw = null;
		try {
			pw = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (pw != null) {
			pw.write(msg);
			pw.close();
		}
	}

	public String importProduct(InputStream stream, HttpServletRequest request)
			throws Exception {
		boolean flag = false;
		List<EntProduct> list = new ArrayList<EntProduct>();
		String orgname = request.getParameter("orgname");
		orgname = new String(orgname.getBytes("ISO-8859-1"), "UTF-8");
		try {
			Workbook book = Workbook.getWorkbook(stream);
			Sheet[] sheets = book.getSheets();
			Sheet sheet = sheets[0];
			int rows = sheet.getRows();// 行
			int cols = sheet.getColumns();// 列
			if (cols == 4) {
				for (int i = 1; i < rows; i++) {
					EntProduct product = new EntProduct();
					product.setName(sheet.getCell(0, i).getContents());
					String categoryName = sheet.getCell(1, i).getContents();
					List categoryList = new ArrayList();
					categoryList.add(categoryName);
					product.setCategoryList(categoryList);
					// product.setCategoryName(sheet.getCell(1,
					// i).getContents());
					product.setDesc(sheet.getCell(2, i).getContents());
					product.setDetails(sheet.getCell(3, i).getContents());
					product.setOrgId(request.getParameter("orgid"));
					product.setCreaterId(request.getParameter("createrId"));
					product.setOrgName(orgname);
					product.setApproveState(1);
					list.add(product);
				}
				Map<String, Object> map = new ProductService().saveImport(list);
				flag = (Boolean) map.get("state");
			} else
				return FORMAR_ERROR;
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				stream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (flag) {
			return OPT_OKMSG;
		} else
			return OPT_ERRORMSG;
	}

	public void exportModel(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		EntProduct model = this.getModel(request, response);
		String strFileName = "productModel.xls";
		response.addHeader("Content-Disposition", "attachment; filename=\""
				+ strFileName + "\"");
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			ServletOutputStream out = response.getOutputStream();

			byte[] buff = new byte[2048];
			int bytesRead;
			bis = new BufferedInputStream(this.getData(model));
			bos = new BufferedOutputStream(out);
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
	}

	private InputStream getData(EntProduct model) throws Exception {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet();
		HSSFRow row = sheet.createRow(0);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("赋码物名称");
		cell = row.createCell(1);
		cell.setCellValue("赋码物类型");
		cell = row.createCell(2);
		cell.setCellValue("赋码物简介");
		cell = row.createCell(3);
		cell.setCellValue("赋码物详情");
		// 创建数据
		List<EntProduct> list = new ArrayList<EntProduct>();
		list.add(model);
		for (int i = 0; i < list.size(); i++) {
			System.out.println("===" + list.size());
			System.out.println("i=" + i);
			row = sheet.createRow(i + 1);
			cell = row.createCell(0);
			cell.setCellValue(list.get(i).getName());
			cell = row.createCell(1);
			cell.setCellValue(list.get(i).getCategoryName());
			cell = row.createCell(2);
			cell.setCellValue(list.get(i).getDesc());
			cell = row.createCell(3);
			// cell.setCellStyle(wb.createCellStyle().setDataFormat(HSSFDataFormat.getBuiltinFormat("yyyy-MM-dd HH:mm:ss")));
			cell.setCellValue(list.get(i).getDetails());
		}
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			wb.write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}

		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		return is;
	}

	private EntProduct getModel(HttpServletRequest request,
			HttpServletResponse response) {
		EntProduct model = new EntProduct();
		model.setId(StringUtil.getNewStr(request.getParameter("ids")));
		return model;
	}

}
